<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Article,App\Category,App\Tag;
use App\Http\Requests,App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;
use Auth,EndaEditor,DB,App\Comment;

class ArticleController extends Controller
{
    /**
     * 文章列表展示.
     *
     * @return Response
     */
    public function index()
    {
        $cates = Category::getCateData();
        
        $articles = Article::NoDel()->paginate(10);

        $tags = Tag::lists('name','id');
        
        return view('admin.articleAdmin',compact('articles','cates','tags'));
    }

    /**
     * 发布文章视图页面.
     *
     * @return Response
     */
    public function create()
    {
        $cates = Category::getCateData();

        $tags = Tag::lists('name','id');
        
        return view('admin.addArticle',compact('cates','tags'));
    }

    /**
     * 创建文章处理.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(ArticleRequest $request)
    {
        $article = Auth::user()->articles()->create( $request->except('_token') );

        if($request->tags){
        	$article->tags()->sync( $request->tags );
        }
        //百度推送
        $result = self::pushBaidu($request->cate_id,$article->id);

        return redirect(url('yhsystem/article'))->withSuccess('发布成功'.$result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        
    }

    /**
     * 编辑文章视图.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $cates = Category::getCateData();

        $article = Article::findOrFail($id);
        
        $taged = [];
        
        foreach($article->tags as $tag){
            $taged[$tag->id] = $tag->name;
        }

        $notag = array_diff( Tag::lists('name','id')->toArray(),$taged );
        
        return view('admin.editArticle',compact('article','taged','notag','cates'));
    }

    /**
     * 编辑文章处理.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(ArticleRequest $request, $id)
    {
        $article = Article::findOrFail($id);
        
        $article->update($request->except(['_token','tags']));

        if($request->tags){
            $article->tags()->sync( $request->tags );
        }
        //百度推送
        $result = self::pushBaidu($request->cate_id,$article->id);

        return redirect()->back()->withSuccess('修改成功'.$result);
    }

    /**
     * 删除文章.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $article = Article::findOrFail($id);

        $content = EndaEditor::MarkDecode($article->content);

        self::delImage($content);
        
        $tagid = DB::table('article_tag')->where('art_id',$id)->pluck('tag_id');
        
        $article->tags()->detach($tagid);
        
        Article::destroy($id);

        Comment::where('art_id',$id)->delete();
        
        return redirect()->back()->withSuccess('删除成功!');
    }
    /**
     * 通过栏目或关键字检索文章
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getCate(Request $request)
    {
        $info = $request->except('_token');

        $cates = Category::getCateData();
        
        $tags = Tag::lists('name','id');

        if($request->cate_id == 0){           
            if($request->keywords){
                $articles = Article::where('del',$info['del'])->where('title','LIKE','%'.$request->keywords.'%')->orderBy('published_at', 'desc')->paginate(5);
            }else{
                return redirect(url('yhsystem/article')); 
            }
        }else{            
            if($request->keywords){
                $articles = Category::find($request->cate_id)->catArticle()->where('del',$info['del'])->where('title','LIKE','%'.$request->keywords.'%')->orderBy('published_at', 'desc')->paginate(5);
            }else{
                $articles = Category::find($request->cate_id)->catArticle()->where('del',$info['del'])->orderBy('published_at', 'desc')->paginate(5);
            }        
        }

        if($info['cate_id'] == 0){
            $info['cate_name'] = '全部';
        }else{
            $info['cate_name'] = Category::where('id',$info['cate_id'])->pluck('cate_name');
        }

        if($info['del'] == 0){
            return view('admin.articleAdmin',compact('articles','cates','tags','info'));
        }else{
            return view('admin.articleDust',compact('articles','cates','tags','info'));
        }
        
    }
    /**
     * 设置文章状态
     * @param Request $request [description]
     */
    public function setStatus(Request $request)
    {
           
        $info = $request->except('_token');

        if( isset($info['ids']) ){
            
            Article::whereIn('id',$info['ids'])->update(['status'=>$info['status']]);

            return redirect()->back()->withSuccess('修改成功');
        }
        
        return redirect()->back()->withError('请先选择要修改的文章');
    }
    /**
     * 图像上传方法
     * @return [type] [description]
     */
    public function upload(){

        $data = EndaEditor::uploadImgFile('uploads');

        return json_encode($data);

    }
    /**
     * 删除图片方法
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    private function delImage($content){
        
        $url="/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/is";

        preg_match_all($url,$content,$res);
        
        if(isset($res[3][0])){
            
            foreach($res[3] as $v){
                
                if( strstr($v,url('/')) ){
                    $str = str_replace(url('/'), '', $v);
                    @unlink(public_path().$str);
                }
                            
            }

        }
        
    }
    /**
     * 回收站
     * @return [type] [description]
     */
    public function dust(){
        $cates = Category::getCateData();
        
        $articles = Article::Del()->paginate(10);

        $tags = Tag::lists('name','id');
        
        return view('admin.articleDust',compact('articles','cates','tags'));
    }
    /**
     * 回收站处理
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function runDust($id){
        $article = Article::find($id);
        
        if($article->del == 0){
            $article->update(['del'=>1]);
        }else{
            $article->update(['del'=>0]);
        }
        
        return redirect()->back()->withSuccess('修改成功');
    }
    public function pushBaidu($cate_id,$id){
        //推送
        $urls = array(
            url('lists'.$cate_id.'/'.$id),
        );
        $api = 'http://data.zz.baidu.com/urls?site=www.yanhai0531.com&token=3bjmODf0iHLDOFhC';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        
        return $result;
    }

}
